<template>
  <div class="f-multi-user-selector-wrapper">
    <el-input v-model="usersNameValue" :disabled="disabled"
              readonly @click="openUserSelectModal"
              clearable class="f-multi-user-selector">
      <template #prefix>
        <div @click="openUserSelectModal" class="selector-button">
          <user/>
        </div>
      </template>
    </el-input>
    <UserSelectModal @ok="selectUserChange" :tabsConfig="tabsConfig"
                     ref="refUserSelectModal"/>
  </div>
</template>
<script setup>
import {computed, shallowRef} from 'vue';
import UserSelectModal from '@/components/SingleUserSelector/UserSelectModal.vue';
import {isEmpty, real} from '@/utils/CommonUtils';

const props = defineProps({
  disabled: false,
  usersId: undefined,
  usersName: undefined,
  tabsConfig: {
    type: Array,
    default: () => []
  }
});

const refUserSelectModal = shallowRef();
const emits = defineEmits(['update:usersId', 'update:usersName']);
const usersNameValue = computed({
  get() {
    return props.usersName;
  },
  set(value) {
    emits('update:usersName', value);
  },
});

function serUsersId(usersId) {
  emits('update:usersId', usersId);
}

function getUsers() {
  let list = [];
  try {
    let ids = props.usersId;
    let usersName = props.usersName;
    ids = ids.split(',');
    usersName = usersName.split(',');

    for (let i = 0; i < ids.length; i++) {
      list.push({
        id: ids[i],
        realname: usersName[i]
      });
    }
  } catch (e) {
  }
  return list;
}

function openUserSelectModal() {
  let users = getUsers();
  refUserSelectModal.value.setData(users);
}

function selectUserChange(users) {
  users = real(users);
  if (isEmpty(users)) users = [];
  let ids = users.map(u => u.id);
  let realnames = users.map(u => u.realname);

  emits('update:usersId', ids.toString());
  emits('update:usersName', realnames.toString());
}

</script>
<script>
import './style.css';

export default {
  name: 'MultiUserSelector'
};
</script>
